import { Exclude } from 'class-transformer'
import { BaseEntity } from 'src/common/base.entity'
import { createPassword } from 'src/common/utils'
import { Item } from 'src/items/entities/item.entity'
import {
  Entity,
  Column,
  BeforeInsert,
  OneToMany,
  OneToOne,
  JoinColumn
} from 'typeorm'
import { Profile } from './profile.entity'
import { Role } from '../enums/role.enum'

@Entity()
export class User extends BaseEntity {
  @Column()
  mobile: string

  @Column()
  @Exclude({ toPlainOnly: true })
  password: string

  @Column({
    type: 'enum',
    enum: Role,
    array: true,
    default: [Role.USER]
  })
  roles: Role[]

  @OneToOne(() => Profile, (profile) => profile.user, {
    eager: true,
    cascade: true
  })
  @JoinColumn()
  profile: Profile

  @OneToMany(() => Item, (item) => item.user)
  items: Item[]

  @BeforeInsert()
  async hashPassword() {
    this.password = await createPassword(this.password)
  }
}
